package org.apache.ocean.database;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.ocean.CLong;
import org.apache.ocean.TransactionID;

/**
 *
 * @author jasonr
 */
public class SQLResults extends ArrayList<SQLRow> {
  private List<String> columnNames;
	
  public SQLResults(List<String> columnNames) {
  	this.columnNames = columnNames;
  }
  
  public List<String> getColumnNames() {
  	return columnNames;
  }
  
  public Object getFirst(Transform transform) throws Exception {
    SQLRow row = getFirstRow();
    if (row != null) return transform.row(row);
    return null;
  }
  
  public List toList(Transform transform) throws Exception {
    List list = new ArrayList(size());
    for (SQLRow row : this) {
      list.add(transform.row(row));
    }
    return list;
  }
  
  public static interface Transform<V> {
    public V row(SQLRow row) throws Exception;
  }
  
  public TransactionID getAggregateTransactionID() {
  	SQLRow row = getFirstRow();
    if (row != null) {
    	BigDecimal count = (BigDecimal)row.get(0);
    	if (count != null) return new TransactionID(count.toBigInteger());
    } 
    return null;
  }
  
  public CLong getAggregateLong() {
  	SQLRow row = getFirstRow();
    if (row != null) {
    	CLong count = (CLong)row.get(0);
    	if (count != null) return count;
    } 
    return new CLong(0);
  }
  
  public int getCount() {
    SQLRow row = getFirstRow();
    if (row != null) {
      Integer count = (Integer)row.get(0);
      return count.intValue();
    } else return 0;
  }
  
  public SQLRow getFirstRow() {
    Iterator<SQLRow> iterator = iterator();
    if (iterator.hasNext()) return iterator.next();
    else return null;
  }
}
